﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint.WebControls;
using System.Data;


namespace Trig_AMJ_IT_Customforms
{
    class SPHelper : Trig_WF
    {

        string ErrorMsgs;
        Demand_Voucher_FormClass objDemand = new Demand_Voucher_FormClass();
        /// <summary>
        /// Generate Request No based on Doc Prefix and Starting No for Master List.
        /// </summary>
        /// <param name="mainLstName"></param>
        /// <param name="lblTxkNo"></param>
        /// <param name="SiteURL"></param>

        #region "IT Forms Auto No Generation"

        public void AutoNoGeneration(string mainLstName, string docTypeLstName, Label requestNo, string SiteURL)
        {
            try
            {
                SPListItem oLstItem = null;
                string RefNo;
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        SPList oList = oWeb.Lists.TryGetList(docTypeLstName);
                        if (oList != null)
                        {
                            // Get starting number from Document Types 
                            oLstItem = GetSPListItem(mainLstName, oList); // Check Master list is in Document Types or not
                            if (oLstItem != null)
                            {
                                int stNo = Convert.ToInt32(oLstItem["Starting Number"]) + 1;
                                RefNo = oLstItem["DocPrefix"] + "/" + DateTime.Now.Year + "/" + Convert.ToString(stNo);
                                requestNo.Text = RefNo;
                                // Update starting number for Document Types 
                                int itmID = Convert.ToInt32(oLstItem["ID"]);
                                SPListItem oLstItemUpt = oList.GetItemById(itmID);
                                oLstItemUpt["Starting Number"] = stNo;
                                oLstItemUpt.Update();
                            }
                            else { RefNo = null; requestNo.Text = null; }
                        }
                        oWeb.AllowUnsafeUpdates = false;
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_IT_Forms" + " :: " + "SPHelper" + " :: " + "AutoNoGeneration";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");

            }

        }

        #endregion

        /// <summary>
        /// Get User Profiles and assign to controls for OnBehalf of users
        /// </summary>
        /// <param name="AccountName"></param>
        /// <param name="name"></param>
        /// <param name="id"></param>
        /// <param name="dept"></param>
        /// <param name="position"></param>
        /// <param name="mob"></param>

        #region "Get User Profiles"

        public void GetCurrentUserDetails(string AccountName, TextBox name, TextBox id, TextBox division, TextBox dept, TextBox position, TextBox mob)
        {
            try
            {
                id.Text = null; dept.Text = null; position.Text = null; mob.Text = null;

                UserProfile userProfile = GetUserInfo(AccountName);

                if (userProfile[PropertyConstants.FirstName].Value != null)
                {
                    if (name != null)
                        name.Text = userProfile[PropertyConstants.FirstName].Value.ToString();
                }
                if (userProfile["EmployeeID"].Value != null)
                {
                    id.Text = userProfile["EmployeeID"].Value.ToString();
                }
                if (userProfile["Division"].Value != null)
                {
                    division.Text = userProfile["Division"].ToString();
                }
                if (userProfile[PropertyConstants.Department].Value != null)
                {
                    dept.Text = userProfile[PropertyConstants.Department].Value.ToString();
                }
                if (userProfile["Designation"].Value != null)
                {
                    position.Text = userProfile["Designation"].Value.ToString();
                }
                if (userProfile[PropertyConstants.CellPhone].Value != null)
                {
                    mob.Text = userProfile[PropertyConstants.CellPhone].Value.ToString();
                }

            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_IT_Forms" + " :: " + "SPHelper" + " :: " + "GetCurrentUserDetails";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

            //try
            //{
            //    imgBtnUserImage.ImageUrl = userProfile[PropertyConstants.PictureUrl].Value.ToString();
            //}
            //catch (Exception ex)
            //{
            //    imgBtnUserImage.ImageUrl = "/_layouts/ExpressionsWP/0.jpg";
            //}

        }

        private UserProfile GetUserInfo(string AccountName)
        {
            UserProfile profile = null;
            SPServiceContext serviceContext = SPServiceContext.Current;
            UserProfileManager profileManager = new UserProfileManager(serviceContext);
            if (AccountName != string.Empty)
            {
                profile = profileManager.GetUserProfile(AccountName);
            }
            else
            {
                profile = profileManager.GetUserProfile(SPContext.Current.Web.CurrentUser.RawSid);
            }
            return profile;
        }

        #endregion

        /// <summary>
        /// IT Helpdesk request categories
        /// Software request categories
        /// </summary>
        /// <param name="ddlReqCategory"></param>
        /// <param name="SiteURL"></param>

        #region "Bind Categories in Dropdown"

        public void GetRequestCategories(string lstCategories, DropDownList ddlReqCategory, string SiteURL)
        {
            try
            {
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        SPList oList = oWeb.Lists.TryGetList(lstCategories);
                        if (oList != null)
                        {
                            SPQuery qry = new SPQuery();
                            qry.Query = "<Where><IsNotNull><FieldRef Name=\"Title\" /></IsNotNull></Where><OrderBy><FieldRef Name=\"LinkTitle\" Ascending=\"True\" /></OrderBy>";
                            qry.ViewFields = "<FieldRef Name='Title' />";
                            SPListItemCollection oLstItems = oList.GetItems(qry);
                            foreach (SPListItem oItem in oLstItems)
                            {
                                ddlReqCategory.Items.Add(oItem.Title);
                            }
                            ddlReqCategory.Items.Insert(0, "Select");
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_IT_Forms" + " :: " + "SPHelper" + " :: " + "GetRequestCategories";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");

            }
        }

        #endregion

        /// <summary>
        /// Add IT Helpdesk and Software Access Request form details
        /// </summary>
        /// <param name="SiteURL"></param>
        /// <param name="MainLstName"></param>
        /// <param name="TaskLstName"></param>
        /// <param name="CmntsLstName"></param>
        /// <param name="onBehalf"></param>
        /// <param name="attLibName"></param>
        /// <param name="fileUploadControl"></param>
        /// <param name="WorkflowConfigList"></param>
        /// <param name="pplcnt"></param>
        /// <param name="cntrls"></param>
        /// <returns></returns>

        #region "Add IT Helpdesk Request Details on Form"

        public string AddITItems(string SiteURL, string MainLstName, string TaskLstName, string CmntsLstName, int onBehalf, string attLibName, FileUpload fileUploadControl, string WorkflowConfigList,
          PeopleEditor pplcnt, params object[] cntrls)
        {
            string lstGuid = null;
            string refNo = (cntrls[0] as string);
            SPWeb oWeb = null;
            SPList oListMain = null; SPList oListTask = null;
            SPFieldUserValue UserName = null;
            #region "Add Items in forms"

            try
            {
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        oListMain = oWeb.Lists.TryGetList(MainLstName);
                        oListTask = oWeb.Lists.TryGetList(TaskLstName);
                        if (oListMain != null)
                        {
                            SPListItem oLstItem = oListMain.Items.Add();

                            oLstItem["Title"] = refNo; // (cntrls[0] as string);
                            oLstItem["Reference Number"] = refNo; // (cntrls[0] as string);
                            oLstItem["RequestDate"] = Convert.ToDateTime((cntrls[1] as string));
                            oLstItem["WFStatus"] = "In Progress";
                            oLstItem["Document Status"] = "In Progress";


                            oWeb.EnsureUser((cntrls[2] as string));
                            SPUser User = oWeb.SiteUsers[(cntrls[2] as string)];
                            UserName = new SPFieldUserValue(oWeb, User.ID, User.Name);

                            oLstItem["RequestedBy"] = UserName;
                            oLstItem["LoggedinID"] = (cntrls[3] as string);
                            oLstItem["LoggedinDivision"] = (cntrls[4] as string);
                            oLstItem["LoggedinDepartment"] = (cntrls[16] as string);
                            oLstItem["LoggedinDesignation"] = (cntrls[5] as string);
                            oLstItem["LoggedinMobileNo"] = (cntrls[6] as string);

                            oLstItem["RequestCategories"] = (cntrls[7] as string);
                            oLstItem["RequestPriority"] = (cntrls[8] as string);
                            oLstItem["RequestDescription"] = (cntrls[9] as string);

                            if (onBehalf == 0)
                            {
                                oLstItem["SubmittedFor"] = UserName;// (cntrls[2] as string);
                                oLstItem["EmployeeID"] = (cntrls[3] as string);
                                oLstItem["Division"] = (cntrls[4] as string);
                                oLstItem["Department"] = (cntrls[16] as string);
                                oLstItem["Designation"] = (cntrls[5] as string);
                                oLstItem["MobileNo"] = (cntrls[6] as string);
                            }
                            else
                            {
                                //string str = (cntrls[10] as string);
                                //string[] str1 = str.Split('\\');

                                oWeb.EnsureUser((cntrls[10] as string));
                                SPUser Users = oWeb.SiteUsers[(cntrls[10] as string)];
                                SPFieldUserValue UserNames = new SPFieldUserValue(oWeb, Users.ID, Users.Name);

                                oLstItem["SubmittedFor"] = UserNames;//Convert.ToString(str1[10]);
                                oLstItem["EmployeeID"] = (cntrls[11] as string);
                                oLstItem["Division"] = (cntrls[15] as string);
                                oLstItem["Department"] = (cntrls[12] as string);
                                oLstItem["Designation"] = (cntrls[13] as string);
                                oLstItem["MobileNo"] = (cntrls[14] as string);
                            }

                            if (onBehalf == 0)
                                oLstItem["OnBehalfof"] = "No";
                            else
                                oLstItem["OnBehalfof"] = "Yes";
                            oLstItem.Update();
                            oWeb.AllowUnsafeUpdates = false;

                            lstGuid = Convert.ToString(oListMain.ID);
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                ErrorMsgs = "Trig_AMJ_IT_Forms" + "::" + "SPHelper" + "::" + "AddITItems";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                //SetErrorLogs(SiteURL, "AddItems", ex.Message, ex.StackTrace);
            }

            #endregion

            if (!string.IsNullOrEmpty(fileUploadControl.FileName))
                AddAttachement(SiteURL, attLibName, refNo, lstGuid, fileUploadControl);

            // Approval user and comments updation
            SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, lstGuid, UserName.LookupValue, (cntrls[17] as string), 0);

            string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;
            string[] WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, false, CurrentUser, false, 0);

            if (Convert.ToString(WFUser[1]) != CurrentUser)
            {
                createTask(oWeb, oListMain, oListTask, WorkflowConfigList, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8]);
            }
            else
            {
                WFUser = new string[10];
                WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, true, CurrentUser, false, 0);
                createTask(oWeb, oListMain, oListTask, WorkflowConfigList, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8]);
            }

            return lstGuid;

        }

        #endregion

        public void RejectForUser(string SiteURL, string MainLstName, string TaskLstName, string CmntsLstName, int onBehalf, string attLibName,
            FileUpload fileUploadControl, string wfConfigLst, string refNo, string lstGuid, string comments, PeopleEditor pplcnt, string TaskItemID)
        {
            SPWeb oWeb = null; SPList oListMain = null; SPList oListTask = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (oWeb = oSite.OpenWeb())
                        {
                            oWeb.AllowUnsafeUpdates = true;
                            oListMain = oWeb.Lists.TryGetList(MainLstName);
                            oListTask = oWeb.Lists.TryGetList(TaskLstName);
                            SPList oLstTask = oWeb.Lists.TryGetList(TaskLstName);
                            lstGuid = Convert.ToString(oListMain.ID);
                            if (oLstTask != null)
                            {
                                //string DVTaskItemID = Convert.ToString(Request.Params["TaskItemID"]);
                                if (!string.IsNullOrEmpty(TaskItemID))
                                {
                                    //lop.Begin();
                                    SPQuery updatecamQ = new SPQuery();
                                    updatecamQ.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + TaskItemID + "</Value></Eq></Where>";
                                    SPListItemCollection TasksListitemcoll = oLstTask.GetItems(updatecamQ);
                                    if (TasksListitemcoll.Count > 0)
                                    {
                                        SPListItem oitm = TasksListitemcoll[0];
                                        oitm["Status"] = "Completed";
                                        oitm["OutCome"] = "Rejected";
                                        oWeb.AllowUnsafeUpdates = true;
                                        oitm.Update();
                                        oWeb.AllowUnsafeUpdates = false;
                                        Demand_Voucher_FormClass obj = new Demand_Voucher_FormClass();
                                        int WFOrder = Convert.ToInt16(oitm["WFCurrentOrder"]);
                                        WFOrder = WFOrder + 1;
                                        obj.UpdateFormStatus(oWeb, wfConfigLst, MainLstName, refNo, WFOrder, false);

                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    ErrorMsgs = "Trig_AMJ_IT_Forms" + " :: " + "SPHelper" + " :: " + "RejectForUser";
                    GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                }

                if (!string.IsNullOrEmpty(fileUploadControl.FileName))
                    AddAttachement(SiteURL, attLibName, refNo, lstGuid, fileUploadControl);

                // Approval user and comments updation

                string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;

                SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, lstGuid, CurrentUser, comments, 0);

                string[] WFUser = CheckCurrentUserAsWFUser(oWeb, wfConfigLst, MainLstName, false, CurrentUser, false, 0);

                if (Convert.ToString(WFUser[1]) != CurrentUser)
                {
                    createTask(oWeb, oListMain, oListTask, wfConfigLst, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8]);
                }
                else
                {
                    WFUser = new string[10];
                    WFUser = CheckCurrentUserAsWFUser(oWeb, wfConfigLst, MainLstName, true, CurrentUser, false, 0);
                    createTask(oWeb, oListMain, oListTask, wfConfigLst, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8]);
                }
            });
        }


        /// <summary>
        /// Add User and Approvers comments
        /// </summary>
        /// <param name="SiteURL"></param>
        /// <param name="cmntsLstName"></param>
        /// <param name="cntrls"></param>

        #region "Add User Comments Data"

        public void SetCommnets(string SiteURL, string cmntsLstName, params object[] cntrls)
        {
            try
            {

                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        SPList oList = oWeb.Lists.TryGetList(cmntsLstName);
                        if (oList != null)
                        {
                            SPListItem oLstItem = oList.Items.Add();
                            oLstItem["Title"] = (cntrls[0] as string);
                            oLstItem["Reference_x0020_Number"] = (cntrls[1] as string);
                            oLstItem["ListID"] = (cntrls[2] as string);
                            oLstItem["CommentByUser"] = (cntrls[3] as string);
                            oLstItem["User_x0020_Comments"] = (cntrls[4] as string);
                            oLstItem["WFCurrentOrder"] = Convert.ToInt32((cntrls[5] as string));
                            oLstItem.Update();
                        }

                        oWeb.AllowUnsafeUpdates = false;
                    }
                }

            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_IT_Forms" + " :: " + "SPHelper" + " :: " + "SetCommnets";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }

        #endregion


        #region "Add Email-ID Request Form"

        public string AddItems(string SiteURL, string MainLstName, string TaskLstName, string CmntsLstName, string attLibName, FileUpload fileUploadControl, string WorkflowConfigList,
          PeopleEditor pplcnt, params object[] cntrls)
        {
            string lstGuid = null;
            string refNo = (cntrls[0] as string);
            SPWeb oWeb = null;
            SPList oListMain = null; SPList oListTask = null;
            SPFieldUserValue UserName = null;

            #region "AddItems"

            try
            {
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        oListMain = oWeb.Lists.TryGetList(MainLstName);
                        oListTask = oWeb.Lists.TryGetList(TaskLstName);
                        if (oListMain != null)
                        {
                            SPListItem oLstItem = oListMain.Items.Add();

                            oLstItem["Title"] = (cntrls[0] as string);
                            oLstItem["Reference Number"] = (cntrls[0] as string);
                            oLstItem["RequestDate"] = Convert.ToDateTime((cntrls[1] as string));
                            oLstItem["WFStatus"] = "In Progress";
                            oLstItem["Document Status"] = "In Progress";

                            oWeb.EnsureUser((cntrls[2] as string));
                            SPUser User = oWeb.SiteUsers[(cntrls[2] as string)];
                            UserName = new SPFieldUserValue(oWeb, User.ID, User.Name);

                            oLstItem["RequestedBy"] = UserName;
                            oLstItem["LoggedinID"] = (cntrls[3] as string);
                            oLstItem["LoggedinDivision"] = (cntrls[4] as string);
                            oLstItem["LoggedinDesignation"] = (cntrls[5] as string);
                            oLstItem["LoggedinMobileNo"] = (cntrls[6] as string);

                            oLstItem["FirstName"] = (cntrls[7] as string);
                            oLstItem["LastName"] = (cntrls[8] as string);
                            oLstItem["Department"] = (cntrls[9] as string);
                            oLstItem["MobileNo"] = (cntrls[10] as string);
                            oLstItem["UserNameSuggestion"] = (cntrls[11] as string);

                            oLstItem["Division"] = (cntrls[13] as string);


                            oLstItem.Update();

                            lstGuid = Convert.ToString(oListMain.ID);

                        }
                        oWeb.AllowUnsafeUpdates = false;
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_IT_Forms :: Email ID Request" + " :: " + "SPHelper" + " :: " + "AddItems";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

            #endregion

            if (!string.IsNullOrEmpty(fileUploadControl.FileName))
                AddAttachement(SiteURL, attLibName, refNo, lstGuid, fileUploadControl);

            // Approval user and comments updation
            SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, lstGuid, UserName.LookupValue, (cntrls[12] as string), 0);

            string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;
            string[] WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, false, CurrentUser, false, 0);

            if (Convert.ToString(WFUser[1]) != CurrentUser)
            {
                createTask(oWeb, oListMain, oListTask, WorkflowConfigList, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8]);
            }
            else
            {
                WFUser = new string[10];
                WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, true, CurrentUser, false, 0);
                createTask(oWeb, oListMain, oListTask, WorkflowConfigList, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8]);
            }

            return lstGuid;

        }

        #endregion

        /// <summary>
        /// Add Attachment to Attachment Libraty
        /// </summary>
        /// <param name="SiteUrl"></param>
        /// <param name="AttachmentsLibrary"></param>
        /// <param name="referenceNumber"></param>
        /// <param name="FormListID"></param>
        /// <param name="fileUploadControl"></param>

        #region "Add Attachment"

        private void AddAttachement(string SiteUrl, string AttachmentsLibrary, string referenceNumber, string FormListID, FileUpload fileUploadControl)
        {
            try
            {
                using (SPSite osite = new SPSite(SiteUrl))
                {
                    using (SPWeb oweb = osite.OpenWeb())
                    {
                        SPDocumentLibrary myLibrary = oweb.Lists[AttachmentsLibrary] as SPDocumentLibrary;
                        byte[] fileBytes = fileUploadControl.FileBytes;
                        string time = DateTime.Now.ToString().Replace("/", "");
                        string strDestUrl = myLibrary.RootFolder.Url + "/" + time.Replace(":", "") + fileUploadControl.FileName;
                        oweb.AllowUnsafeUpdates = true;
                        SPFile destFile = myLibrary.RootFolder.Files.Add(strDestUrl, fileBytes, true);
                        destFile.Item["ListID"] = FormListID;
                        destFile.Item["Reference_x0020_Number"] = referenceNumber;
                        SPUser ouser = oweb.EnsureUser(SPContext.Current.Web.CurrentUser.Name);
                        destFile.Item["UploadByUser"] = ouser;
                        destFile.Update();
                        destFile.Item.Update();
                        destFile.Update();
                        oweb.AllowUnsafeUpdates = false;
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_IT_Forms" + " :: " + "SPHelper" + " :: " + "AddAttachement";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }

        #endregion

        /// <summary>
        /// check current user configured in the Workflow config list as a first item of the DV form
        /// </summary>
        /// <param name="oweb"></param>
        /// <returns></returns>

        #region "CheckCurrentUserAsWFUser"

        private string[] CheckCurrentUserAsWFUser(SPWeb oweb, string WorkflowConfigList, string mainLstName, bool currentUserExist, string currentUser, bool approval, int WFCurrentOrder)
        {
            string[] orderNum = new string[10];
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    if (oweb.Lists.TryGetList(WorkflowConfigList) != null)
                    {
                        SPQuery oqry = new SPQuery();
                        if (currentUserExist)
                        {
                            oqry.Query = "<Where><And><Eq><FieldRef Name='Optional' /><Value Type='Boolean'>0</Value></Eq><And>"
                                + "<Neq><FieldRef Name='Send_x0020_to_x0020_Users' /><Value Type='User'>" + currentUser + "</Value></Neq><Eq><FieldRef Name='Doctype' />"
                                + "<Value Type='Lookup'>" + mainLstName + "</Value></Eq></And></And></Where>";
                        }
                        else if (approval)
                        {
                            oqry.Query = "<Where><And><Eq><FieldRef Name='Order0' /><Value Type='Number'>" + WFCurrentOrder + "</Value></Eq><Eq><FieldRef Name='Doctype' /><Value Type='Lookup'>" + mainLstName + "</Value></Eq></And></Where>";
                        }
                        else
                        {
                            oqry.Query = "<Where><Eq><FieldRef Name='Doctype' /><Value Type='Lookup'>" + mainLstName + "</Value></Eq></Where>";
                        }

                        if (oweb.Lists.TryGetList(WorkflowConfigList).GetItems(oqry).Count > 0)
                        {
                            SPListItem oitm = oweb.Lists.TryGetList(WorkflowConfigList).GetItems(oqry)[0];
                            orderNum[0] = Convert.ToString(oitm["Order0"]);
                            if (!string.IsNullOrEmpty(Convert.ToString(oitm["Send_x0020_to_x0020_Users"])))
                            {
                                SPFieldUserValue ofluser = new SPFieldUserValue(oweb, Convert.ToString(oitm["Send_x0020_to_x0020_Users"]));
                                orderNum[1] = ofluser.User.Name;
                            }
                            orderNum[2] = Convert.ToBoolean(oitm["Optional"]).ToString();
                            orderNum[3] = Convert.ToString(oitm["Task_x0020_type"]);
                            orderNum[4] = Convert.ToString(oitm["UPAttributeName"]);
                            orderNum[5] = Convert.ToString(oitm["ECListName"]);
                            orderNum[6] = Convert.ToString(oitm["ECFieldName"]);
                            orderNum[7] = Convert.ToString(oitm["ECMatchField"]);
                            orderNum[8] = Convert.ToString(oitm["ECUPMatchField"]);
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_IT_Forms" + " :: " + "SPHelper" + " :: " + "CheckCurrentUserAsWFUser";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

            return orderNum;

        }

        #endregion

        /// <summary>
        /// Approve the form
        /// </summary>

        #region "Approve Form"

        public string ApprovetheForm(string SiteURL, string MainLstName, string TaskLstName, string wfConfigLst, string CmntsLstName, string AttLibName, string FormID, string refNo,
            string TaskItemID, string WFTaskType, string ApprovalUser, string comments, FileUpload fileUploadControl, RadioButton rtbForwardOthers, RadioButton rtbSendBack,
            PeopleEditor pplcnt, bool AssignTosubmitUser)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {

                            SPList oLstTask = oWeb.Lists.TryGetList(TaskLstName);
                            SPList oLstForm = oWeb.Lists.TryGetList(MainLstName);
                            if (oLstTask != null && oLstForm != null)
                            {
                                FormID = Convert.ToString(oLstForm.ID);
                                //string DVTaskItemID = Convert.ToString(Request.Params["TaskItemID"]);
                                if (!string.IsNullOrEmpty(TaskItemID))
                                {
                                    //lop.Begin();
                                    SPQuery updatecamQ = new SPQuery();
                                    updatecamQ.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + TaskItemID + "</Value></Eq></Where>";
                                    SPListItemCollection TasksListitemcoll = oLstTask.GetItems(updatecamQ);
                                    if (TasksListitemcoll.Count > 0)
                                    {
                                        SPListItem oitm = TasksListitemcoll[0];
                                        oitm["Status"] = "Completed";
                                        oitm["OutCome"] = "Approved";
                                        oWeb.AllowUnsafeUpdates = true;
                                        oitm.Update();
                                        oWeb.AllowUnsafeUpdates = false;
                                        WFTaskType = Convert.ToString(oitm["WFTaskType"]);
                                        int WFOrder = 0;
                                        WFOrder = Convert.ToInt16(oitm["WFCurrentOrder"]);

                                        SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, FormID, ApprovalUser, comments, WFOrder);

                                        if (!string.IsNullOrEmpty(fileUploadControl.FileName))
                                            AddAttachement(SiteURL, AttLibName, refNo, FormID, fileUploadControl);

                                        if (rtbForwardOthers.Checked || rtbSendBack.Checked)
                                        {
                                            WFOrder = Convert.ToInt16(oitm["WFCurrentOrder"]);
                                            if (rtbForwardOthers.Checked)
                                            {
                                                createTask(oWeb, oLstForm, oLstTask, wfConfigLst, pplcnt, WFOrder, "", true, false, WFTaskType, refNo, "", "", "", "");
                                            }
                                            else if (rtbSendBack.Checked && !AssignTosubmitUser)
                                            {

                                                createTask(oWeb, oLstForm, oLstTask, wfConfigLst, pplcnt, WFOrder, "", false, true, WFTaskType, refNo, "", "", "", "");
                                            }
                                        }
                                        else if (AssignTosubmitUser)
                                        {
                                            SPFieldUserValue user = GetSubmittedUser(SiteURL, FormID, refNo);
                                            if (user.LookupValue.ToLower() == SPContext.Current.Web.CurrentUser.LoginName.ToLower())
                                            {
                                                objDemand.UpdateFormStatus(oWeb, wfConfigLst, MainLstName, refNo, WFOrder, false);
                                            }
                                            else
                                            {
                                                WFOrder = Convert.ToInt16(oitm["WFCurrentOrder"]);
                                                string[] WFUser = CheckCurrentUserAsWFUser(oWeb, wfConfigLst, MainLstName, false, ApprovalUser, true, WFOrder);
                                                createTasktoUsers(oWeb, oLstForm, oLstTask, GetSubmittedUser(SiteURL, FormID, refNo), refNo, WFOrder, WFUser[3], AssignTosubmitUser);
                                            }
                                        }
                                        else
                                        {
                                            WFOrder = Convert.ToInt16(oitm["WFCurrentOrder"]) + 1;
                                            string[] WFUser = CheckCurrentUserAsWFUser(oWeb, wfConfigLst, MainLstName, false, ApprovalUser, true, WFOrder);
                                            createTask(oWeb, oLstForm, oLstTask, wfConfigLst, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8]);

                                            int cnt = GetWFConfigCnt(wfConfigLst, MainLstName, SiteURL);
                                            if (cnt != 0 && cnt == 1)
                                            {
                                                objDemand.UpdateFormStatus(oWeb, wfConfigLst, MainLstName, refNo, Convert.ToInt16(oitm["WFCurrentOrder"]), false);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }


                });


            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_IT_Forms" + " :: " + "SPHelper" + " :: " + "ApprovetheForm";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
            return FormID;
        }

        #endregion


        public void CreateEmailAccounts(string SiteURL, string refNo, string FormID, params string[] cntrls)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
               {
                   using (SPSite oSite = new SPSite(SiteURL))
                   {
                       using (SPWeb oWeb = oSite.OpenWeb())
                       {
                           oWeb.AllowUnsafeUpdates = true;
                           SPQuery qry = new SPQuery();
                           qry.Query = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refNo + "</Value></Eq></Where>";
                           SPListItem oItem = oWeb.Lists[new Guid(FormID)].GetItems(qry)[0];
                           oItem["UserName"] = (cntrls[0] as string);
                           oItem["EmailAddress"] = (cntrls[1] as string);
                           oItem["Password"] = (cntrls[2] as string);
                           oItem.Update();
                           oWeb.AllowUnsafeUpdates = false;
                       }
                   }
               });
        }

        private int GetWFConfigCnt(string wfConfigLst, string MainLstName, string SiteURL)
        {
            SPListItemCollection itmColl = null;
            string qry = "<Where><Eq><FieldRef Name=\"Doctype\" /><Value Type=\"Lookup\">" + MainLstName + "</Value></Eq></Where>";
            int cnt = 0;

            try
            {
                itmColl = GetSPListItems(SiteURL, wfConfigLst, qry);
                cnt = itmColl.Count;
            }
            catch (Exception)
            {
                cnt = 0;
            }
            return cnt;
        }


        public SPListItemCollection GetSPListItems(string SiteURL, string lstName, string camlQry)
        {
            SPListItemCollection oLstItemColl = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            oWeb.AllowUnsafeUpdates = true;
                            SPList oList = oWeb.Lists.TryGetList(lstName);
                            if (oList != null)
                            {
                                SPQuery qry = new SPQuery();
                                qry.Query = camlQry;
                                oLstItemColl = oList.GetItems(qry);
                            }
                        }
                    }

                }
                catch (Exception ex)
                {
                    ErrorMsgs = "Trig_AMJ_IT_Forms" + " :: " + "SPHelper" + " :: " + "GetSPListItems";
                    GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                }
            });
            return oLstItemColl;
        }

        public SPListItem GetSPListItem(string SiteURL, string lstName, string camlQry)
        {
            SPListItem oLstItem = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            oWeb.AllowUnsafeUpdates = true;
                            SPList oList = oWeb.Lists.TryGetList(lstName);
                            if (oList != null)
                            {
                                SPQuery qry = new SPQuery();
                                qry.Query = camlQry;
                                oLstItem = oList.GetItems(qry)[0];
                            }
                        }
                    }

                }
                catch (Exception ex)
                {
                    ErrorMsgs = "Trig_AMJ_IT_Forms" + " :: " + "SPHelper" + " :: " + "GetSPListItem";
                    GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                }

            });
            return oLstItem;
        }

        private SPListItem GetSPListItem(string mainLstName, SPList oList)
        {
            SPListItem oLstItem = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    SPQuery qry = new SPQuery();
                    qry.Query = "<Where><Eq><FieldRef Name=\"Title\" /><Value Type=\"Text\">" + mainLstName + "</Value></Eq></Where>";
                    oLstItem = oList.GetItems(qry)[0];
                }
                catch (Exception ex)
                {
                    oLstItem = null;
                }
            });
            return oLstItem;
        }

        #region "GetSubmittedUser"
        /// <summary>
        /// Get submitted user (Created By) from corresponding forms
        /// </summary>
        /// <param name="SiteURL"></param>
        /// <param name="listID"></param>
        /// <param name="refNo"></param>
        /// <returns></returns>
        public SPFieldUserValue GetSubmittedUser(string SiteURL, string listID, string refNo)
        {

            SPFieldUserValue userValue = null;
            try
            {
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        if (listID != null)
                        {
                            SPList oList = oWeb.Lists[new Guid(listID)];
                            if (oList != null)
                            {
                                SPQuery qry = new SPQuery();
                                qry.Query = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refNo + "</Value></Eq></Where>";
                                qry.ViewFields = "<FieldRef Name='RequestedBy' />";
                                SPListItem oLstItems = oList.GetItems(qry)[0];
                                userValue = new SPFieldUserValue(SPContext.Current.Web, oLstItems["RequestedBy"].ToString());
                            }
                        }
                        oWeb.AllowUnsafeUpdates = false;
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_IT_Forms" + " :: " + "UserProfileInfo" + " :: " + "GetSubmittedUser";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
            return userValue;
        }


        #endregion


        public void GetApprovedUsers(string refNo, string SiteURL, string TaskLstName, GridView gvApprovers)
        {
            SPListItemCollection oItemColl = null;
            string camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refNo + "</Value></Eq></Where>" +
                "<OrderBy><FieldRef Name=\"Modified\" Ascending=\"False\" /></OrderBy>";
            oItemColl = GetSPListItems(SiteURL, TaskLstName, camlQry);
            DataTable dt = new DataTable();
            // dt.Columns.Add("Approved By");
            DataRow dr;

            using (SPSite oSite = new SPSite(SiteURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    if (oItemColl.Count > 0)
                    {
                        foreach (SPListItem oItem in oItemColl)
                        {
                            SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, Convert.ToString(oItem["AssignedTo"]));
                            dt.Columns.Add(oItem["ID"].ToString());
                        }

                        dr = dt.NewRow();
                        int wfCnt = dt.Columns.Count;
                        int i = 0;
                        foreach (SPListItem oItem in oItemColl)
                        {
                            if (i < wfCnt)
                            {
                                SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, Convert.ToString(oItem["AssignedTo"]));
                                if (Convert.ToString(fldUser.LookupValue).Contains("\\"))
                                {
                                    string user = Convert.ToString(fldUser.LookupValue);
                                    string[] users = user.Split('\\');
                                    int arrLenth = users.Length;
                                    if (arrLenth > 0)
                                        dr[i] = users[1];
                                    else
                                        dr[i] = users[0];
                                }
                                i++;
                            }
                        }
                        dt.Rows.Add(dr);
                        i = 0;
                        dr = dt.NewRow();
                        while (i < wfCnt)
                        {
                            dr[i] = "Approved By";
                            i++;
                        }
                        dt.Rows.Add(dr);
                        gvApprovers.DataSource = dt;
                        gvApprovers.DataBind();
                        gvApprovers.HeaderRow.Visible = false;
                    }

                }

            }

        }
    }
}
